/***************************************
 * @update: 2021-05-26  LiLinBin  [添加'openPageToBlank']
 * @update: 2021-07-09   LiLinBin  [添加findComp函数]
 * 
 * @description: 页面处理工具
 ***************************************/


import router from 'router/index'


/**
* 打开一个新的页面
* @param path
* @param query
*/
const openPageToBlank = function (path, query) {
    let routeUrl = router.resolve({
        path: path,
        query: query
    });
    window.open(routeUrl.href, '_blank');
}



/**
* 查找页面中指定的组件实例对象 (用于注入脚本时)
* @param desNameId [String]
* @return 组件实例 [Object]
* this [需要指向此函数所作用的组件对象]
* 例如: findComp.call(this, desNameId)
*/
const findComp = function (desNameId) {
    if (!desNameId) return

    const pParent = this.$parent
    // const pParent = parent && parent.$parent
    const refs = pParent && pParent.$refs

    if (!refs) return

    const key = `comp_${desNameId}`
    const target = refs[key]

    if (target) return Array.isArray(target) ? target[0] : target

    //递归查找
    const find = (pParent) => {
        const ppParent = pParent.$parent
        if (!ppParent) return

        const obj = ppParent.$refs[key]
        if (obj) return Array.isArray(obj) ? obj[0] : obj
        else return find(ppParent)
    }

    return find(pParent)
}

const getPageRender = function () {
    const parent = this.$parent
    const pParent = parent && parent.$parent
    const refs = pParent && pParent.$refs

    if (!refs) return

    const key = "preview";
    const target = refs[key]

    if (target) return Array.isArray(target) ? target[0] : target

    //递归查找
    const find = (pParent) => {
        const ppParent = pParent.$parent
        if (!ppParent) return

        const obj = ppParent.$refs[key]
        if (obj) return Array.isArray(obj) ? obj[0] : obj
        else return find(ppParent)
    }

    return find(pParent)
}

const showPageByPageId = function (pageId) {
    var pageRender = getPageRender.call(this);
    if (!pageRender || !pageRender.showPageByPageId) {
        var root = this.$root;
        var currentRoute = root.$router.currentRoute;
        console.log(currentRoute);
    }
    if (pageRender && pageRender.showPageByPageId) {
        pageRender.showPageByPageId(pageId);
    }
}



/**
 * 打印组件信息
 * 使用: consoleDesName.call(this)
 */
const consoleDesName = function consoleDesName () {
    console.log('\n')
    console.log(`所在的组件: des -> ${this.$options.des}; componentName -> ${this.$options.name}`)
}



export function exitLogin () { }




export {
    openPageToBlank,
    findComp,
    showPageByPageId,
    consoleDesName
}